import { Component, OnInit, Output, EventEmitter, Input, ViewChild, TemplateRef, HostBinding } from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { IdService } from '@farris/ui-common';
import { DatagridComponent } from '@farris/ui-datagrid';
import { EditorTypes } from '@farris/ui-datagrid-editors';
import { ControlService } from '../../../../../service/control.service';
import { DgControl } from '../../.../../../../../utils/dg-control';


export class StepMessage {
  id: string;
  title: string;
  icon: string;

  constructor(id: string, title: string, icon: string) {
    this.id = id;
    this.title = title;
    this.icon = icon;
  }
}



@Component({
  selector: 'app-progress-steps-editor',
  templateUrl: './progress-steps-editor.component.html',
  styleUrls: ['./progress-steps-editor.component.css']
})
export class ProgressStepsEditorComponent implements OnInit {


  @Output() closeModal = new EventEmitter<any>();
  // 模态框确定后关闭，并传递参数
  @Output() submitModal = new EventEmitter<any>();
  @Input() value: StepMessage[];
  @Input() editorParams = { wizardPages: [], activeIndex: 0 };


  @ViewChild('itemsFooter') modalFooter: TemplateRef<any>;
  modalConfig = {
    title: '步骤条编辑器',
    width: 900,
    height: 500,
    showButtons: true
  };
  /** 数据源 用来保存过程中编辑数据  */
  data: StepMessage[];

  @ViewChild('dg') dg: DatagridComponent;

  columns = [
    { field: 'id', title: '值', editor: { type: EditorTypes.TEXTBOX } },
    { field: 'title', title: '名称', editor: { type: EditorTypes.TEXTBOX } },
    { field: 'icon', title: '图标', editor: { type: EditorTypes.TEXTBOX } }
  ];


  @HostBinding('class')
  class = 'd-flex f-utils-fill-flex-column h-100';

  constructor(
    private notifyService: NotifyService,
    private controlServ: ControlService,
    private idServ: IdService) { }

  ngOnInit() {
    if (!this.value || this.value.length === 0) {
      this.data = [];
      return;
    }
    this.data = Object.assign([], this.value);
    this.data.forEach((v: any) => {
      v.hId = this.idServ.generate();
    });
  }

  clickCancel() {
    this.closeModal.emit();
  }

  clickConfirm() {

    // 触发单元格结束编辑
    this.dg.endEditing();

    // 获取最新数组
    const latestData = [];
    this.dg.data.forEach(d => {
      const { hId, ...other } = d;
      latestData.push(other);
    });

    // 校验
    if (!this.checkBeforeSave(latestData)) {
      return;
    }


    const newWizardPages = this.assembleWizardPages(latestData);
    if (latestData.length > 0 && this.editorParams.activeIndex > latestData.length - 1) {
      this.notifyService.warning('请重新设置【默认显示页面索引】属性');
    }
    // parameters 数组传递新向导页数据wizardPages
    this.submitModal.emit({ value: latestData, parameters: newWizardPages });
  }


  private assembleWizardPages(latestData: StepMessage[]): any[] {
    if (!latestData || latestData.length === 0) {
      return [];
    }
    const oldPages = this.editorParams.wizardPages;
    const newPages = [];
    latestData.forEach(step => {
      const page = oldPages.find(p => p.id === step.id);
      if (page) {
        page.name = step.title;
        newPages.push(page);
      } else {
        // 新建步骤，默认预置详情页，详情页中预置外部组件。
        const pageMetadata = this.controlServ.getControlMetaData(DgControl.WizardDetailContainer.type);
        pageMetadata.id = step.id;
        pageMetadata.name = step.title;
        const wizardDetail = pageMetadata.contents[0];
        wizardDetail.id = wizardDetail.id + '_' + step.id;
        wizardDetail.footerTemplate = "<div class=\"f-template-wizard-page-footer\">    \r\n\t<button class=\"btn btn-secondary f-btn-ml\" [disabled]=\"viewModel.uiState.disableCancel\" (click)=\"viewModel.cancelWizard1()\">\r\n        取消\r\n    </button>\r\n\t<button class=\"btn btn-secondary f-btn-ml\" [disabled]=\"viewModel.uiState.disablePre\" (click)=\"viewModel.preStep1()\">\r\n        上一步\r\n    </button>\r\n\t<button class=\"btn btn-primary f-btn-ml\" [disabled]=\"viewModel.uiState.disableNext\" (click)=\"viewModel.nextStep1()\">\r\n        下一步\r\n    </button>\r\n    <button class=\"btn btn-primary f-btn-ml\" [disabled]=\"viewModel.uiState.disableFinish\" (click)=\"viewModel.finishWizard1()\">\r\n        完成\r\n    </button>\r\n</div>";
        const externalContainer = this.controlServ.getControlMetaData(DgControl.ExternalContainer.type);
        externalContainer.id = externalContainer.id + '_' + step.id;
        externalContainer.appearance = {
          class: 'h-100 position-relative'
        };
        wizardDetail.contents.push(externalContainer);
        newPages.push(pageMetadata);
      }
    });
    return newPages;
  }

  /**
   * 保存前检查
   */
  checkBeforeSave(latestData: StepMessage[]): boolean {
    // ① 空
    if (!latestData || latestData.length === 0) {
      this.notifyService.warning('请添加值。');
      return false;
    }
    // ② 非空，则校验每个的键值是否为空；
    for (const item of latestData) {
      if (!item.id || !item.title) {
        this.notifyService.warning('值和名称均不允许为空。');
        return false;
      }
    }
    // ③ 键不允许重复；
    const itemKeys = latestData.map(e => e.id);
    const keySet = new Set(itemKeys);
    const exclusiveKeys = Array.from(keySet);
    if (itemKeys.length !== exclusiveKeys.length) {
      this.notifyService.warning('值不允许重复。');
      return false;
    }

    return true;

  }

  /**
   * 新增值
   */
  addHandler() {

    // 触发单元格结束编辑
    this.dg.endEditing();

    const newData = new StepMessage('', '', '');
    this.dg.appendRow({
      hId: this.idServ.generate(),
      ...newData
    });
  }

  /**
   * 删除
   */
  removeHandler(): void {


    // 触发单元格结束编辑
    this.dg.endEditing();

    const row = this.dg.selectedRow;
    if (row) {
      this.dg.deleteRow(row.id);
      this.dg.clearSelections();
    } else {
      this.notifyService.warning('请选中要删除的行');
    }
  }
}


